/*
 * @lc app=leetcode.cn id=1624 lang=typescript
 *
 * [1624] 两个相同字符之间的最长子字符串
 */

// @lc code=start
function maxLengthBetweenEqualCharacters(s: string): number {
  const idx = new Map<string, number[]>();
  const n = s.length;
  for (let i = 0; i < n; i++) {
    if (!idx.has(s[i])) {
      idx.set(s[i], []);
    }
    idx.get(s[i])!.push(i);
  }

  let ans = -1;
  for (const [_, v] of idx.entries()) {
    if (v.length > 1) {
      ans = Math.max(ans, v[v.length - 1] - v[0] - 1);
    }
  }

  return ans;
}
// @lc code=end
